﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 采购退货服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class SalesReturnService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<SalesReturn> _salesReturnRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public SalesReturnService(SqlSugarRepository<SalesReturn> salesReturnRep, ISqlSugarClient sqlSugarClient)
    {
        _salesReturnRep = salesReturnRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询采购退货 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询采购退货")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<SalesReturnOutput>> Page(PageSalesReturnInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _salesReturnRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.SalesReturnCode.Contains(input.Keyword) || u.Desc.Contains(input.Keyword) || u.TotalPrices.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.SalesReturnCode), u => u.SalesReturnCode.Contains(input.SalesReturnCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Desc), u => u.Desc.Contains(input.Desc.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.TotalPrices), u => u.TotalPrices.Contains(input.TotalPrices.Trim()))
            .WhereIF(input.VendorId != null, u => u.VendorId == input.VendorId)
            .WhereIF(input.PurchaseOrderId != null, u => u.PurchaseOrderId == input.PurchaseOrderId)
            .WhereIF(input.WarehouseId != null, u => u.WarehouseId == input.WarehouseId)
            .LeftJoin<Vendor>((u, vendor) => u.VendorId == vendor.Id)
            .LeftJoin<Purchaseorder>((u, vendor, purchaseOrder) => u.PurchaseOrderId == purchaseOrder.Id)
            .LeftJoin<Warehouse>((u, vendor, purchaseOrder, warehouse) => u.WarehouseId == warehouse.Id)
            .Select((u, vendor, purchaseOrder, warehouse) => new SalesReturnOutput
            {
                Id = u.Id,
                SalesReturnCode = u.SalesReturnCode,
                VendorId = u.VendorId,
                VendorFkDisplayName = $"{vendor.VendorName}",
                PurchaseOrderId = u.PurchaseOrderId,
                PurchaseOrderFkDisplayName = $"{purchaseOrder.Odd}",
                SalesReturnDate = u.SalesReturnDate,
                Desc = u.Desc,
                WarehouseId = u.WarehouseId,
                WarehouseFkDisplayName = $"{warehouse.WarehouseName}",
                TotalPrices = u.TotalPrices,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取采购退货详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取采购退货详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<SalesReturn> Detail([FromQuery] QueryByIdSalesReturnInput input)
    {
        return await _salesReturnRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加采购退货 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加采购退货")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddSalesReturnInput input)
    {
        var entity = input.Adapt<SalesReturn>();
        return await _salesReturnRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新采购退货 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新采购退货")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateSalesReturnInput input)
    {
        var entity = input.Adapt<SalesReturn>();
        await _salesReturnRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除采购退货 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除采购退货")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteSalesReturnInput input)
    {
        var entity = await _salesReturnRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _salesReturnRep.FakeDeleteAsync(entity);   //假删除
        //await _salesReturnRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除采购退货 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除采购退货")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteSalesReturnInput> input)
    {
        var exp = Expressionable.Create<SalesReturn>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _salesReturnRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _salesReturnRep.FakeDeleteAsync(list);   //假删除
        //return await _salesReturnRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataSalesReturnInput input)
    {
        var vendorIdData = await _salesReturnRep.Context.Queryable<Vendor>()
            .InnerJoinIF<SalesReturn>(input.FromPage, (u, r) => u.Id == r.VendorId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.VendorName}"
            }).ToListAsync();
        var purchaseOrderIdData = await _salesReturnRep.Context.Queryable<Purchaseorder>()
            .InnerJoinIF<SalesReturn>(input.FromPage, (u, r) => u.Id == r.PurchaseOrderId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.Odd}"
            }).ToListAsync();
        var warehouseIdData = await _salesReturnRep.Context.Queryable<Warehouse>()
            .InnerJoinIF<SalesReturn>(input.FromPage, (u, r) => u.Id == r.WarehouseId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.WarehouseName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "vendorId", vendorIdData },
            { "purchaseOrderId", purchaseOrderIdData },
            { "warehouseId", warehouseIdData },
        };
    }
    
    /// <summary>
    /// 导出采购退货记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出采购退货记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageSalesReturnInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportSalesReturnOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "采购退货导出记录");
    }
    
    /// <summary>
    /// 下载采购退货数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载采购退货数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportSalesReturnOutput>(), "采购退货导入模板", (_, info) =>
        {
            if (nameof(ExportSalesReturnOutput.VendorFkDisplayName) == info.Name) return _salesReturnRep.Context.Queryable<Vendor>().Select(u => $"{u.VendorName}").Distinct().ToList();
            if (nameof(ExportSalesReturnOutput.PurchaseOrderFkDisplayName) == info.Name) return _salesReturnRep.Context.Queryable<Purchaseorder>().Select(u => $"{u.Odd}").Distinct().ToList();
            if (nameof(ExportSalesReturnOutput.WarehouseFkDisplayName) == info.Name) return _salesReturnRep.Context.Queryable<Warehouse>().Select(u => $"{u.WarehouseName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入采购退货记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入采购退货记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportSalesReturnInput, SalesReturn>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 供应商
                    var vendorIdLabelList = pageItems.Where(x => x.VendorFkDisplayName != null).Select(x => x.VendorFkDisplayName).Distinct().ToList();
                    if (vendorIdLabelList.Any()) {
                        var vendorIdLinkMap = _salesReturnRep.Context.Queryable<Vendor>().Where(u => vendorIdLabelList.Contains($"{u.VendorName}")).ToList().ToDictionary(u => $"{u.VendorName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.VendorId = vendorIdLinkMap.GetValueOrDefault(e.VendorFkDisplayName ?? "");
                            if (e.VendorId == null) e.Error = "供应商链接失败";
                        });
                    }
                    // 链接 采购编号
                    var purchaseOrderIdLabelList = pageItems.Where(x => x.PurchaseOrderFkDisplayName != null).Select(x => x.PurchaseOrderFkDisplayName).Distinct().ToList();
                    if (purchaseOrderIdLabelList.Any()) {
                        var purchaseOrderIdLinkMap = _salesReturnRep.Context.Queryable<Purchaseorder>().Where(u => purchaseOrderIdLabelList.Contains($"{u.Odd}")).ToList().ToDictionary(u => $"{u.Odd}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.PurchaseOrderId = purchaseOrderIdLinkMap.GetValueOrDefault(e.PurchaseOrderFkDisplayName ?? "");
                            if (e.PurchaseOrderId == null) e.Error = "采购编号链接失败";
                        });
                    }
                    // 链接 仓库
                    var warehouseIdLabelList = pageItems.Where(x => x.WarehouseFkDisplayName != null).Select(x => x.WarehouseFkDisplayName).Distinct().ToList();
                    if (warehouseIdLabelList.Any()) {
                        var warehouseIdLinkMap = _salesReturnRep.Context.Queryable<Warehouse>().Where(u => warehouseIdLabelList.Contains($"{u.WarehouseName}")).ToList().ToDictionary(u => $"{u.WarehouseName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.WarehouseId = warehouseIdLinkMap.GetValueOrDefault(e.WarehouseFkDisplayName ?? "");
                            if (e.WarehouseId == null) e.Error = "仓库链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<SalesReturn>>();
                    
                    var storageable = _salesReturnRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.SalesReturnCode?.Length > 32, "退货编号长度不能超过32个字符")
                        .SplitError(it => it.Item.Desc?.Length > 32, "备注长度不能超过32个字符")
                        .SplitError(it => it.Item.TotalPrices?.Length > 32, "总价长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
